#include "Model.h"
#include "Vertex.h"
#include "string.h"

char* Model::GetID()
{
	return ID;
}
void Model::LoadModel(const char* ID, char* file)
{
	strcpy(this->ID, ID);

	unsigned short p1, p2, p3;
	FILE * pFile;
	pFile = fopen(file, "r");
	int numVertices;
	fscanf(pFile, "NrVertices: %d\n",&numVertices);
	Vertex * verticesData = new Vertex[numVertices];
	int temp = 0;
	for (int i = 0; i < numVertices; i++)
	{
		fscanf(pFile," %d. pos:[%f, %f, %f]; norm:[%f, %f, %f]; binorm:[%f, %f, %f]; tgt:[%f, %f, %f]; uv:[%f, %f];\n",
			&temp,
			&verticesData[i].pos.x, &verticesData[i].pos.y, &verticesData[i].pos.z,
			&verticesData[i].normal.x, &verticesData[i].normal.y, &verticesData[i].normal.z,
			&verticesData[i].binormal.x, &verticesData[i].binormal.y, &verticesData[i].binormal.z,
			&verticesData[i].tangent.x, &verticesData[i].tangent.y, &verticesData[i].tangent.z,
			&verticesData[i].uv.x, &verticesData[i].uv.y
			);
	}
	fscanf(pFile, "NrIndices: %d\n",&m_numIndices);
	unsigned short * indices = new unsigned short[m_numIndices];

	int cnt = 0;
	for (; cnt < m_numIndices; )
	{
		fscanf(pFile,"   %d.    %hu,    %hu,    %hu\n",
			&temp, &p1, &p2, &p3
		);
			indices[cnt++] = p1;
			indices[cnt++] = p2;
			indices[cnt++] = p3;
	}

	//buffer object
	glGenBuffers(1, &vboId);
	glBindBuffer(GL_ARRAY_BUFFER, vboId);
	glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(Vertex), verticesData, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	
	glGenBuffers(1, &vboId2);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboId2);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_numIndices * sizeof(unsigned short), indices, GL_STATIC_DRAW);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	delete[] verticesData;
	delete[] indices;
	delete[] file;

}

int Model::GetNumIndices()
{
	return m_numIndices;
}

Model::Model(void)
{
}

Model::~Model(void)
{
	glDeleteBuffers(1, &vboId);
	glDeleteBuffers(1, &vboId2);

}
